package handler

import (
	"github.com/gin-gonic/gin"
	"proj-dev-mgmt/model"
	"strconv"
)

func Article(c *gin.Context) {
	title := c.PostForm("title")
	price := c.PostForm("price")
	new_count := c.PostForm("new_count")
	if title == "" || price == "" || new_count == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}
	data := model.Article{
		Title:    title,
		Price:    price,
		NewCount: new_count,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var date []model.Article

	model.DB.Offset(offset).Limit(size).Find(&date)

	var todel int64

	model.DB.Model(&model.Article{}).Count(&todel)

	c.JSON(200, gin.H{
		"code":   200,
		"msg":    "查询成功",
		"data":   date,
		"offset": offset,
		"todel":  todel,
	})
	return
}
